package cn.dongjak.example.spring.security.config;

import cn.dongjak.example.spring.security.service.ExampleUserDetailsService;
import cn.dongjak.example.spring.security.vo.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

@Configuration
@EnableWebSecurity
@Profile("rest")
@Slf4j
public class RestSecurityConfiguration extends WebSecurityConfigurerAdapter {

    //密码加密器
    private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    private final AccessDeniedHandler restAccessDeniedHandler = (request, response, accessDeniedException) ->
            response.getWriter().write(ApiResponse.builder()
                    .code(403)
                    .message(accessDeniedException.getMessage())
                    .build().toJsonString());
    private final AuthenticationEntryPoint restAuthenticationEntryPoint = (request, response, authException) -> response.getWriter().write(ApiResponse.builder()
            .code(403)
            .message(authException.getMessage())
            .build().toJsonString());
    private final AuthenticationSuccessHandler authenticationSuccessHandler = (request, response, authentication) -> response.getWriter().write(ApiResponse.builder()
            .code(1)
            .message(((UserDetails) authentication.getPrincipal()).getUsername())
            .build().toJsonString());
    private final AuthenticationFailureHandler authenticationFailureHandler = (request, response, exception) -> response.getWriter().write(ApiResponse.builder()
            .code(0)
            .message(exception.getMessage())
            .build().toJsonString());


    private final ExampleUserDetailsService exampleUserDetailsService;

    public RestSecurityConfiguration(ExampleUserDetailsService exampleUserDetailsService) {
        this.exampleUserDetailsService = exampleUserDetailsService;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //region 新增测试用的内存用户
        auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder)
                .withUser("admin")
                .password(passwordEncoder.encode("123394"))
                .roles("USER", "ADMIN");
        //endregion

        auth.userDetailsService(exampleUserDetailsService).passwordEncoder(passwordEncoder);

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.formLogin()
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler);
        http.exceptionHandling()
                // 已登入用户的权限错误
                .accessDeniedHandler(restAccessDeniedHandler)
                // 未登入用户的权限错误
                .authenticationEntryPoint(restAuthenticationEntryPoint);

        http.csrf().disable();
    }


}
